package handler

import (
	"biz-manager/cache"
	"biz-manager/moder"
	"biz-manager/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}

	redis_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"mas":  "密码错误3次",
			"code": 500,
		})
		return
	}

	var user moder.User

	err := moder.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "查询失败",
			"code": 500,
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"mas":  "密码或用户名错误",
			"code": 500,
		})
		return
	}

	if user.Password != pkg.MD(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"mas":  "密码错误3次，封禁2小时",
				"code": 500,
			})
			return
		}
		c.JSON(200, gin.H{
			"mas":  "密码错误",
			"code": 500,
		})
		return

	}

	c.JSON(200, gin.H{
		"mas":  "密码正确",
		"code": 200,
		"data": user,
	})
	return

}

func RodeNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := moder.RodeNode{
		Rid: rid,
		Nid: nid,
	}

	err := moder.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "分配失败",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return

}

func UserRode(c *gin.Context) {
	uid := c.Query("uid")

	var data []moder.Rode
	moder.DB.Table("rodes").
		Joins("LEFT JOIN user_rodes ON user_rodes.rid = rodes.id").
		Where("user_rodes.uid =?", uid).
		Debug().
		Find(&data)

	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return

}

func RodeNode(c *gin.Context) {
	rid := c.Query("rid")
	var data []moder.Node
	moder.DB.Table("nodes").
		Joins("LEFT JOIN rode_nodes ON rode_nodes.nid = nodes.id").
		Where("rode_nodes.rid = ?", rid).
		Debug().
		Find(&data)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return
}
